package com.lifeng.mynetty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lifeng
 * 2017/9/1 14:59
 */
public class TcpServerHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(HttpServerHandler.class);
    private String charset;

    public TcpServerHandler() {
    }

    public TcpServerHandler(String charset) {
        this.charset = charset;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if(msg instanceof ByteBuf) {
            ByteBuf buf = (ByteBuf) msg;
            byte[] dst = new byte[buf.capacity()];
            buf.readBytes(dst);
            logger.info("SERVER接收到消息:" + new String(dst,charset));
            ByteBuf resp = Unpooled.copiedBuffer(("你好:"+new String(dst,charset)).getBytes(charset));
            ctx.write(resp);
        }
        if(msg instanceof String){
            String body = (String)msg;
            logger.info("收到客户端信息:"+body);
            ByteBuf resp = Unpooled.copiedBuffer(("你好:"+body).getBytes(charset));
            ctx.writeAndFlush(resp);
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error(cause.getMessage());
        ctx.close();
    }
}
